package lrparser.parser;

import lrparser.parser.CodeScanner;
import lrparser.parser.Word;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;

/**
 * 词法分析器
 */
public class WordAnalyzer {
	private final File inputFile;
	private final File outputFile;
	private final ArrayList<Word> list = new ArrayList<>();

	public WordAnalyzer(String input,String output) {
		inputFile = new File(input);
		outputFile = new File(output);
	}

	/**
	 * 从指定的文件中读取源程序文件内容
	 */
	public String getContent() {
		StringBuilder stringBuilder = new StringBuilder();
		try(Scanner reader = new Scanner(inputFile)) {
			while (reader.hasNextLine()) {
				String line = reader.nextLine();
				stringBuilder.append(line + "\n");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}
	/**
	 * 先将源程序中的注释和换行替换成空串
	 * 然后扫描程序，在程序结束前将扫描到的词添加到list中
	 * 最后把扫描结果保存到指定的文件中
	 */
	public void analyze(String fileContent) {
		int over = 1;
		Word word = new Word();
		CodeScanner scanner = new CodeScanner(fileContent.toCharArray());
		while (over != 0) {
			word = scanner.scan();
			list.add(word);
			over = word.getTypenum();
		}
		saveResult();
	}
	/**
	 * 将结果写入到到指定文件中
	 * 如果文件不存在，则创建一个新的文件
	 * 用一个foreach循环将list中的项变成字符串写入到文件中
	 */
	public void saveResult() {
		if (!outputFile.exists()) {
			try {
				outputFile.createNewFile();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		try(Writer writer = new FileWriter(outputFile)){
			for (Word word : list) {
				writer.write("(" + word.getTypenum() + " ," + word.getWord() + ")\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public ArrayList<Word> getList() {
		return list;
	}
}
